<template>
  <div class="app-page">
    <div class="table">
      <el-table-form ref="form">
        <el-form-item class="merge-item">
          <el-select v-model="qtype" style="width: 180px; margin-right: 2px;">
            <el-option label="客户编号" value="csmCode" />
            <el-option label="客户名称" value="csmName" />
            <el-option label="客户组号" value="csmCode1" />
            <el-option label="客户组名称" value="csmName1" />
            <el-option label="充值卡号" value="cardCode" />
            <el-option label="电话" value="csmPhone" />
          </el-select>
          <el-input v-model.trim="qtTxt" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item class="merge-item">
          <el-select v-model="orgtype" style="width: 180px; margin-right: 2px;">
            <el-option label="销卡机构" value="refundOrgSNNo" />
            <el-option label="开卡机构" value="orgSNNo" />
          </el-select>
          <el-tree-select
            v-model="orgSNNo"
            :clearable="true"
            class="tree-select"
            :popover-width="360"
            :select-params="{
              clearable: false,
              placeholder: '请选择销卡机构',
            }"
            :tree-params=" {
              'expand-on-click-node': false,
              'highlight-current': true,
              props:{
                value:'orgSNNo',
                label: 'orgName',
                disabled: 'disabled',
              },
              data: treeData
            }"
          />
        </el-form-item>
        <el-form-item label="销卡日期:" :table-form-merge="2">
          <el-date-picker
            v-model="date"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            unlink-panels
          />
        </el-form-item>
        <el-form-item label="打印状态:">
          <el-select v-model="query.printStatus" clearable placeholder="请选择">
            <el-option
              v-for="item in printStatuslList"
              :key="item.value"
              :label="item.desc"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <template v-slot:btns>
          <el-button v-permission="[90404, 1]" type="primary" icon="el-icon-search" @click="search">查询</el-button>
        </template>
      </el-table-form>
      <lb-table
        ref="lbTable"
        v-loading="$loadingPlugin.fetchData"
        v-el-height-adaptive-table="{bottomOffset:10}"
        class="cancelCard"
        border
        highlight-current-row
        element-loading-text="加载中"
        :column="column"
        :data="tableData.data"
        pagination
        :total="tableData.total"
        custom-column
        :row-class-name="seRowClass"
        @fetch="fetchData"
      />
    </div>
    <crad-info ref="cradInfo" :tree-data="treeData" :deal-map="dealMap" />
    <csm-detail
      ref="csmDetail"
      :parent-fetch-data="search"
    />
  </div>
</template>

<script>
  import { convertCurrency, formatColumnMap, parseTime } from '@/utils'
  import { getRefundDetail, refundListQuery, topUpAdministrationInfoInfo, updatePrintStatus } from '@/api'
  import moment from 'dayjs'
  import CradInfo from './components/CradInfo.vue'
  import CsmDetail from '@/views/components/CsmDetailModal/index.vue'

  export default {
    name: 'cancelCard',
    components: { CradInfo, CsmDetail },
    props: {
      treeData: {
        type: Array,
        required: true
      },
      dealMap: {
        type: Array,
        required: true
      }
    },

    data() {
      return {
        query: {
          printStatus: ''
        },
        qtTxt: '',
        qtype: 'csmCode',
        orgtype: 'refundOrgSNNo',
        orgSNNo: '',
        date: [new Date(), new Date()],
        tableData: {
          total: 0,
          data: []
        },
        printStatuslList: [
          {
            desc: '已打印',
            value: 2
          },
          {
            desc: '未打印',
            value: 1
          }
        ]
      }
    },
    computed: {
      column: function() {
        return [
          {
            prop: 'cardCode',
            label: '充值卡号',
            width: 150,
            render: (h, { row }) => (
              row.cardCode ? <el-link underline={false} onClick={() => this.csmcardDetail(row)}>
                {row.cardCode}
              </el-link> : <span>{row.cardCode}</span>
            )
          },
          {
            prop: 'csmCode',
            label: '客户编号/组号',
            width: 150,
            render: (h, { row }) => (
              row.csmCode && row.cardOpenStatus === 1 ? <el-link underline={false} onClick={() => this.openCsm(row)}>
                {row.csmCode}
              </el-link> : <span>{row.csmCode}</span>
            )
          },
          {
            prop: 'csmName',
            label: '客户名称/组名称',
            width: 150
          },
          {
            prop: 'openOrgName',
            label: '开卡机构',
            width: 150
          },
          {
            prop: 'refundTime',
            label: '销卡日期',
            width: 150,
            render: (h, { row }) => <span>{ row.refundTime && parseTime(row.refundTime, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
          },
          {
            prop: 'createUser',
            label: '销卡人',
            width: 100
          },
          {
            prop: 'mustMoney',
            label: '销卡应退金额',
            width: 100,
            render: (h, { row }) => <span>{row.mustMoney && this.numberFormat1(row.mustMoney)}</span>
          },
          {
            prop: 'realMoney',
            label: '销卡实退金额',
            width: 100,
            render: (h, { row }) => <span>{row.realMoney && this.numberFormat1(row.realMoney)}</span>

          },
          {
            prop: 'orgName',
            label: '销卡机构',
            width: 150
          },
          {
            prop: 'printStatus',
            width: 100,
            label: '打印状态',
            render: (h, { row }) =>
              <span>
                {row.printStatus &&
                  formatColumnMap(this.printStatuslList, 'value', row.printStatus, 'desc')}
              </span>
          },
          {
            prop: 'remark',
            label: '备注',
            width: 150
          },
          {
            label: '操作',
            align: 'center',
            fixed: 'right',
            render: (h, { row, $index }) => {
              return (
                <div>
                  { <el-link size='mini' v-permission={[90404, 2]} onClick={() => this.onPrint(row)}>打印</el-link> }
                </div>
              )
            }
          }
        ]
      }
    },
    async created() {},
    methods: {
      async fetchData({ currentPage, pageSize }) {
        const query = {
          params: {
            ...this._getQuery(this.query)
          },
          currentPage,
          pageSize
        }

        if (this.qtTxt) {
          if (this.qtype === 'csmCode1') {
            query.params.csmCode = this.qtTxt
            query.params.cardOpenStatus = 2
          } else if (this.qtype === 'csmName1') {
            query.params.csmName = this.qtTxt
            query.params.cardOpenStatus = 2
          } else {
            query.params[this.qtype] = this.qtTxt
            query.params.cardOpenStatus = 1
          }
        }
        if (this.orgtype) {
          query.params[this.orgtype] = this.orgSNNo
        }
        if (this.date && this.date.length === 2) {
          query.params.refundTime = moment(this.date[0]).format('YYYY-MM-DD') + ' ' + '00:00:00'
          query.params.refundTimeEnd = moment(this.date[1]).format('YYYY-MM-DD') + ' ' + '23:59:59'
        } else {
          query.params.refundTime = null
          query.params.refundTimeEnd = null
        }
        const res = await refundListQuery(query)
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
      },
      // 打印
      async onPrint(row) {
        const param = {
          cardCode: row.cardCode
        }
        const res = await getRefundDetail(param)
        if (res && res.data) {
          this.print(res.data)
        }
      },
      async print(row2) {
        const row = JSON.parse(JSON.stringify(row2))
        const cache = JSON.parse(localStorage.tp)
        if (!cache) {
          this.$message.warning('请先设置打印模板')
          return
        }
        const temp = cache['43']
        if (!temp) {
          this.$message.warning('请先设置打印模板')
          return
        }
        const r = {
          csmCode: row.csmCode,
          refundTime: parseTime(new Date(row.refundTime), '{y}-{m}-{d} {h}:{i}:{s}'),
          csmName: row.csmName,
          realMoneyUppercase: convertCurrency((row.realMoney * 1.00 / 100)),
          realMoney: (row.realMoney * 1.00 / 100),
          remark: row.remark,
          createUser: row.createUser
        }
        console.log(r)

        let printcmd = {
          cmd: 2,
          title: `正在对预付卡销卡${r.cardCode}进行打印`,
          elements: []
        }
        printcmd = { ...printcmd, ...temp }
        window.jCPrint.process(printcmd, temp, r)
        delete printcmd.els
        if (window.jCPrint.firePush(JSON.stringify(printcmd))) {
          this.$message.success('打印指令已发送')
          await updatePrintStatus({ optFlag: 3, cardCode: row.cardCode, recordId: row.recordId })
        } else {
          this.$message.error('打印未连接')
        }
      },

      // 清除对象空属性
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      // 查询
      async search() {
        await this.$refs.lbTable.fetch({ currentPage: 1 })
      },

      // 充值金额
      numberFormat1: function(val) {
        val = val * 1.00 / 100
        val = Number(val)
        val = isNaN(val) ? '0.00' : val.toFixed(2)
        return val + ' 元'
      },
      seRowClass({ row, rowIndex }) {
        if (row.printStatus === 2) {
          // 已打印
          return 'print-row'
        }
      },
      // 充值卡详情
      async csmcardDetail(row) {
        const { data } = await topUpAdministrationInfoInfo({ cardCode: row.cardCode })
        await this.$refs.cradInfo.open(data)
      },
      // 打开客户
      async openCsm(row) {
        await this.$refs.csmDetail.open(row, true)
      }
    }
  }
</script>

<style lang="scss" scoped>

</style>
